function init() {
    resetParams();
    getInvoiceList();
}

function renderSheet() {
    
    removeInsertedNodes();

    entityInit['invoice'] = {};
    entityUpdate = {};
   
    renderOrders();

    for (var j in entity) {
	    for (var i in entity[j]) {
		    try {
		        var element = document.getElementById(i);
		
    		    element.innerHTML = entity[j][i];

        		element.contentEditable = 'true';								// 編集を可能にする
        		element.onblur = function(event) { blur(event, this.id); }				// 編集を終了してカーソルが離れたとき
    	    	element.oncontextmenu = function(event) { rightClick(event); }  // 右クリックメニュー用

                entityInit[j][i] = entity[j][i];

        	} catch (e) {
        		// HTMLにない要素をスキップする
	        }
        }
    }
}

function renderOrders() {
	// 対象テーブル内の TR ノード
	trlist = document.getElementsByTagName("TR");

    try {
	    for ( var i = 0; i < trlist.length; i++ ) {
		    if (trlist[i].className=='_for') {
			    // 行数
		    	var valuekey = trlist[i].getAttribute("value");
                //valuekey = record
    			//var value = eval('entity.invoice.'+valuekey);

	    		var value = entity['invoice'][valuekey];
                if (value == undefined) {
                    alert('entity[\'invoice\'][' + valuekey + ']が設定されていません');
                } else {
			
		    	for ( var t = value.length; t > 0; t-- ) {
			    	var trreal = getTrreal(t, trlist[i], value, valuekey);
                
                    //mura
                    trreal.id = PREFIX_TR_INSERTED + t;


				    trlist[i].parentNode.insertBefore( trreal,trlist[i] );
			    }
			    
                break; 
                }
            }
	    }
    } catch(e) {
        alert('EXCEPTION at renderOrders(): ' + e);
    }
}

function getTrreal(n, tr, value, valuekey) {

		var tdlist = tr.getElementsByTagName('TD');
		var trclone = document.createElement('TR'); 

		for (var j = 0; j < tdlist.length; j++) {

			if (tdlist[j]) {
		    var tdclone = tdlist[j].cloneNode(true);
		    
				var tdchildren = tdclone.childNodes;

				for (var k = 0; k < tdchildren.length; k++) {
					if (tdchildren[k].id) {
						
						// hoge-iをhoge-nに変更する
						var tdcid = tdchildren[k].id.replace("-i", "-" + n).replace("-" + (n+1), "-" + n);
						
						if (tdcid.indexOf(valuekey) < 0) {
							tdchildren[k].id = valuekey + "-" + tdcid;
						} else {
							tdchildren[k].id = tdcid;
						}
						
						try {
							// -nとvaluekeyを除いてentityのidを求める
							var id = tdcid.replace("-"+n,"").replace(valuekey+"-","");
                            
							tdchildren[k].innerHTML = value[n-1][id];

                            //mura
                            if (entityInit['invoice'][valuekey] == undefined) {
                                entityInit['invoice'][valuekey] = {};
                            }
                            if (entityInit['invoice'][valuekey][n-1] == undefined) {
                                entityInit['invoice'][valuekey][n-1] = {};
                            }
                            entityInit['invoice'][valuekey][n-1][id] = value[n-1][id];


							tdchildren[k].contentEditable = 'true'; // 編集を可能にする
				    		tdchildren[k].onblur = function(event) { 
                                // 編集を終了してカーソルが離れたとき
                                blur(event, this.id); 
                            }
    						tdchildren[k].oncontextmenu = function(event) { 
                                // 右クリックメニュー用
                                rightClick(event); 
                            }

						} catch (e) {

                        }
					}
				}
				trclone.appendChild(tdclone);
			}
		}
		
	return trclone;
}

function unload() {
    //alert("unload");
}



function blur(event, id) {
 
 	if (event) {
 	
 		var token = event.target.id.split("-");

		if (token.length > 2) {
            //id例）record-description-1

			// update用entityを更新
			//eval("entity.invoice." + token[0] + "[" + (eval(token[2])-1) + "]." + token[1] + " = event.target.innerHTML");
           
            var i = token[2] - 1;

            if (entityInit['invoice'][token[0]][i][token[1]] == event.target.innerHTML) {
                //alert('NOT CHANGED:' + '[' + token[0] + ']' + '[' + i + ']' + '[' + token[1] + '] ' + entityInit['invoice'][token[0]][i][token[1]] + " == " + event.target.innerHTML);
			    
                entity['invoice'][token[0]][i][token[1]] = entityInit['invoice'][token[0]][i][token[1]];
            } else {
                //alert('CHANGED blur: ' + '[' + token[0] + ']' + '[' + i + ']' + '[' + token[1] + '] ' + entityInit['invoice'][token[0]][i][token[1]] + " --> " + event.target.innerHTML);
			    entity['invoice'][token[0]][i][token[1]] = event.target.innerHTML;
            }
		} else {
            if (entityInit['invoice'][id] == document.getElementById(id).innerHTML) {
                //alert('NOT CHANGED:' + '[' + id + '] ' + entityInit['invoice'][id] + " == " + document.getElementById(id).innerHTML);
                entity['invoice'][id] = entityInit['invoice'][id];

            } else {
                //alert('CHANGED blur: ' + '[' + id + '] ' + entityInit['invoice'][id] + " --> " + document.getElementById(id).innerHTML);
                entity['invoice'][id] = document.getElementById(id).innerHTML;
            }
		}
		
		// entityの値と比較して変更があればコピーしてdirtyフラグを立てる
		// 右クリック＝＞保存でdirtyであれば非同期にサーバに保存する。そしてdirty = false(clean)にする
 	}
 	
}

function rightClick(event) {
    //alert("right click:" + event.target.id);
}

function getInsertedNodesCount() {
	var list = document.getElementsByTagName('TR');
    var len = list.length;
    var count = 0;
	for (var i = 0; i < len; i++) {
        if (list[i].id.substr(0, PREFIX_TR_INSERTED.length) == PREFIX_TR_INSERTED) {
            ++count;
        }
    }
    return count;
}

function getNextInsertedNodesCount() {
    var i = getInsertedNodesCount();
    return ++i;
}


function removeInsertedNodes() {
	var list = document.getElementsByTagName('TR');
    var len = list.length;
    var targetNodes = [];
    var targetNodesCounter = 0;
	for (var i = 0; i < len; i++) {
        if (list[i].id == undefined) {
            continue;
        } else {
            var id = list[i].id;
            var node = document.getElementById(id);

            if (id.substr(0, PREFIX_TR_INSERTED.length) == PREFIX_TR_INSERTED) {
                targetNodes[targetNodesCounter++] = node;
            }
        }
	}
    var len = targetNodes.length; 
    for (var i = 0; i < len; i++) {
        var node = targetNodes[i];
        node.parentNode.removeChild(node);
    }
}

function doDelete() {
    if (entity.invoice == undefined || entity.invoice.invoiceNo == undefined) {
        alert('invoiceNo が設定されていません');
    } else {
        del(entity.invoice.invoiceNo);  
        createDeleted();
    }
}


function doContext() {
    //doUpdate();
    //doDelete();
    //doSearch();
    //doPost();
    doContextMenu();
}

function doContextMenu() {
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	var lightboxTop  = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - 0) / 2);
	var lightboxLeft = ((arrayPageSize[0] - 20 - 0) / 2);
    
    var objBody = document.getElementsByTagName('body').item(0);

    var objOverlay = createOverlay();
	objBody.insertBefore(objOverlay, objBody.firstChild);

	var objLightbox = createLightbox(lightboxTop, lightboxLeft);

	var objLightboxContent = document.createElement('div');
	objLightboxContent.setAttribute('id','lightboxcontent');


    var obj = {};

    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'Close';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
        return false;
    }
    objLightboxContent.appendChild(obj); 

    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'New';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
	    var objLightbox = document.getElementById('lightbox');
        removeElement(objLightbox);

        var oInputInvoiceNoDiv = document.createElement('div');
        oInputInvoiceNoDiv.setAttribute('id','lightbox');
        oInputInvoiceNoDiv.style.position = 'absolute';
        oInputInvoiceNoDiv.style.zIndex = '100';
        oInputInvoiceNoDiv.style.backgroundColor = '#eeeeee';
        oInputInvoiceNoDiv.style.border = '2px #006699 solid';
        oInputInvoiceNoDiv.style.width = '200px';
        oInputInvoiceNoDiv.style.height = '200px';
        oInputInvoiceNoDiv.style.display = 'block';
        oInputInvoiceNoDiv.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
        oInputInvoiceNoDiv.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px"

        var input = document.createElement('input');
        input.type = 'text';
        input.id = 'inputInvoiceNo';
        input.name = 'invoiceNo';
        input.value = 'HOGEHOGE';
        input.size = '15';

        var obj = document.createElement('div');
        obj.onclick = function() {
            var invoiceNo = document.getElementById('inputInvoiceNo').value;
            //alert('inputInvoiceNo: ' + invoiceNo);
            hideLightbox();
            post(invoiceNo);
        }
        obj.innerHTML = 'check';
        obj.style.border = '2px #000000 solid'
        obj.style.width = '10em';
        obj.style.cursor = 'pointer';
        obj.id = 'btnPost';
       
        oInputInvoiceNoDiv.appendChild(input);
        oInputInvoiceNoDiv.appendChild(obj);

	    objBody.insertBefore(oInputInvoiceNoDiv, objOverlay.nextSibling);
        return false;
    }
    objLightboxContent.appendChild(obj); 

//Search
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'Search';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {

        getInvoiceList();

	    var objLightbox = document.getElementById('lightbox');
        removeElement(objLightbox);

        //関数化する場合は座標位置を変更すること
        var lightbox = document.createElement('div');
        lightbox.setAttribute('id','lightbox');
        lightbox.style.position = 'absolute';
        lightbox.style.zIndex = '100';
        lightbox.style.backgroundColor = '#ffff00';
        lightbox.style.border = '2px #006699 solid';
        lightbox.style.width = '200px';
        lightbox.style.height = '200px';
        lightbox.style.display = 'block';
        lightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
        lightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px"

        var len = entities.length;
        for (var i = 0; i < len; i++) {
            var div = document.createElement('div');
           
            var invoiceNo = entities[i]['invoiceNo'];
            div.id = invoiceNo; 
            div.style.backgroundColor = '#000000';
            div.style.color = '#00ff00';
            div.onmouseover = function() {
                this.style.backgroundColor = '#333333';
                this.style.color = '#ffff00';
                this.style.cursor = 'pointer';
            }
            div.onmouseout = function() {
                this.style.backgroundColor = '#000000';
                this.style.color = '#00ff00';
            }
            div.onclick = function() {
                hideLightbox();
                read('invoiceNo', this.id);
            }

            div.innerHTML = invoiceNo;
            lightbox.appendChild(div);
        }

	    objBody.insertBefore(lightbox, objOverlay.nextSibling);
    }
    objLightboxContent.appendChild(obj);

//Update
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'Update';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
        doUpdate();
    }
    objLightboxContent.appendChild(obj); 

//Delete
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'Delete';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
        doDelete();
    }
    objLightboxContent.appendChild(obj); 

    objLightbox.appendChild(objLightboxContent);
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);

//PDF
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = 'PDF';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
        //pdf(entity['invoice']['invoiceNo']);
        var url = 'http://pdf.latest.reflex-itext.appspot.com/pdfservicegae?template=' + document.URL + '&entity=http://invoice.latest.reflexcontainer.appspot.com/invoice?invoiceNo=' + entity['invoice']['invoiceNo'] + '&xml'
        location.replace(url);
    }
    objLightboxContent.appendChild(obj); 

    objLightbox.appendChild(objLightboxContent);
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);

//insertOrder
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = '行追加';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
        insertOrder();
    }
    objLightboxContent.appendChild(obj); 
    
//removeOrder
    obj = {};
    obj = document.createElement('div');
    obj.innerHTML = '行削除';
    obj.onmouseout = function() {
        this.style.backgroundColor = '#eeeeee';
    }
    obj.onmouseover = function() {
        this.style.backgroundColor = '#cccccc';
        this.style.cursor = 'pointer';
    }
    obj.onclick = function() {
        hideLightbox();
    }
    objLightboxContent.appendChild(obj); 

}



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function removeLightbox() {
    var objLightbox = document.getElementById('lightbox');
    removeElement(objLightbox);
}

function doUpdate() {

    var isUpdate = false;
    for (var j in entity) {
	    for (var i in entity[j]) {

            if (i == KEY.MEISAI) {
                var len = entity[j][i].length;
                for (var k = 0; k < len; k++) {

                    for (var l in entity[j][i][k]) {

                        if (entityInit[j][i][k][l] == entity[j][i][k][l]) {

                        } else {
                            if (entityUpdate[j] == undefined) {
                                entityUpdate[j] = {};
                            }
                            if (entityUpdate[j][i] == undefined) {
                                entityUpdate[j][i] = [];
                            }
                            if (entityUpdate[j][i][k] == undefined) {
                                entityUpdate[j][i][k] = {};
                            }
                        
                            entityUpdate[j][i][k][l] = entity[j][i][k][l];
                            isUpdate = true;
                            //alert('CHANGED: ' + entityInit[j][i][k][l] + " --> " + entity[j][i][k][l]);
                        }
                    }
                }
            } else if (i == KEY.REVISION) {
                /* revisionには手を加えずにupdateする
                 * updateに成功したらJavascript側でインクリメントする
                 *
                 */
                if (entityUpdate[j] == undefined) {
                    entityUpdate[j] = {};
                }
                entityUpdate[j][i] = entity[j][i];
            } else if (i == KEY.ID) {
                entityUpdate[j][i] = entity[j][i];
            } else if (i == KEY.DELETED) {
                //送信しない
            } else if (i == KEY.INVOICE_NO) {
                if (entityUpdate[j] == undefined) {
                    entityUpdate[j] = {};
                }
                entityUpdate[j][i] = entity[j][i];
            } else {
                if (entityInit[j][i] == entity[j][i]) {
                    //alert('same: ' + entityInit[j][i] + "==" + entity[j][i]); 
                } else {
                   
                    if (entityUpdate[j] == undefined) {
                        entityUpdate[j] = {};
                    }
                    entityUpdate[j][i] = entity[j][i];
                    isUpdate = true;
                    //alert('CHANGED: ' + entityInit[j][i] + " --> " + entity[j][i]);
                }
            }
        }
    }

    if (isUpdate) {
        update(entityUpdate);
    } else {
        alert('変更箇所が無いためアップデートは実行されませんでした');
    }
    
}

function resetParams() {
    entity       = {};
    entityInit   = {};
    entityUpdate = {};
    entities     = [];
}


////
function hideLightbox()
{

    try {
    	// get objects
    	objOverlay = document.getElementById('overlay');
    	objLightbox = document.getElementById('lightbox');

    	// hide lightbox and overlay
    	objOverlay.style.display = 'none';
    	objLightbox.style.display = 'none';
        
        removeElement(document.getElementById('lightbox'));
        removeElement(document.getElementById('overlay'));


    } catch (e) {
    }

	document.onkeypress = '';
}

////

function removeElement(obj) {
    obj.parentNode.removeChild(obj);
}

function createOverlay() {
	var objOverlay = document.createElement('div');
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {
        hideLightbox();
        return false;
    }
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
 	objOverlay.style.backgroundColor = '#000000';
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
    objOverlay.style.MozOpacity = 0.8;
    //objOverlay.style.opacity = 0.8;
    //objOverlay.style.filter = 'alpha(opacity=50)';
	objOverlay.oncontextmenu = function (event) {
        event.stopPropagation();
        event.preventDefault();
        //alert('objOverlay right click');
        return false;
    }    
    return objOverlay;
}



function createLightbox(lightboxTop, lightboxLeft) {
	var objLightbox = document.createElement('div');
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
 	objLightbox.style.backgroundColor = '#eeeeee';
 	objLightbox.style.border = '2px #006699 solid';
 	objLightbox.style.width = '200px';
 	objLightbox.style.height = '200px';
	objLightbox.style.display = 'block';
	objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
	objLightbox.oncontextmenu = function (event) {
        event.stopPropagation();
        event.preventDefault();
        //alert('objLightbox right click');
        return false;
    }
    
    return objLightbox;
}

function createDeleted() {
    var body = document.getElementById('body');
    var page = document.getElementById('pageA4');
    var overlay = document.getElementById('overlay');
    var lightbox = document.getElementById('lightbox');
    body.removeChild(page);

    if (overlay != null) {
        body.removeChild(overlay);
    }

    if (lightbox != null) {
        body.removeChild(lightbox);
    }

    body.style.border = '0px solid #ffffff';
    body.innerHTML = 'deleted.';
}

function insertOrder() {
    getInsertedNodesCount();
    var f = document.getElementById('_for');
    
    var tr = document.createElement('tr');
    tr = f.cloneNode(true);

    var id = PREFIX_TR_INSERTED + getNextInsertedNodesCount();
    tr.className = id;
    tr.id = id;

    tr.style.backgroundColor = getRandomRGB();

    tr.oncontextmenu = function(_event) {
        _event.stopPropagation();
        _event.preventDefault();
        
        this.parentNode.removeChild(this);
        
/*
        var str = '';
        for (var i in _event) {
            str += i + ': ' + _event[i] + '<br>'; 
        }

        //alert(_event.target.className + '/' + _event.target.id);
        //alert(_event.currentTarget.className + '/' + _event.currentTarget.id);
*/
    }

    f.parentNode.insertBefore(tr, f);
}

function removeOrder() {

}
